package datas

import (
	"encoding/json"
	"io"
	"log"
	"os"
	"path"
)

func JsonRecv(con io.ReadWriteCloser, display ...bool) (jsonData Data) {
	// defer con.Close()
	buf := make([]byte, 2048)
	n, err := con.Read(buf)
	// log.Println(string(buf[:n]))
	if err != nil && n <= 0 {
		log.Println("read from sock err:", err)
		return
	}
	jsonData = make(Data)
	err = json.Unmarshal(buf[:n], &jsonData)
	if err != nil {
		con.Write([]byte("Error for recv data!:" + string(buf[:n])))
		con.Close()
		jsonData = nil
	}
	if display != nil {
		log.Println(display)
	}
	return
}

func JsonErr(err error, con io.WriteCloser) {
	JsonSend(Data{
		"Code": false,
		"Err":  err.Error(),
	}, con)
}

func JsonSend(data Data, con io.WriteCloser) (n int) {
	// defer con.Close()
	buf, err := json.Marshal(&data)
	if err != nil {
		log.Println("json tra err:", err)
	}
	// log.Println(string(buf))
	n, err = con.Write([]byte(buf))
	if err != nil {
		log.Println("Send to sock err:", err)
		con.Close()
		n = -1
		return
	}
	return
}

func Daemon(args []string, logFile string) {
	// defer os.Remove(LOG_FILE)
	if os.Getppid() != 1 {
		createLogFile := func(fileName string) (fd *os.File, err error) {
			dir := path.Dir(fileName)
			if _, err = os.Stat(dir); err != nil && os.IsNotExist(err) {
				if err = os.MkdirAll(dir, 0755); err != nil {
					return
				}
			}

			if fd, err = os.Create(fileName); err != nil {
				return
			}
			return
		}
		if logFile != "" {
			logFd, err := createLogFile(logFile)
			if err != nil {
				return
			}
			defer logFd.Close()

			cmdName := args[0]
			newProc, err := os.StartProcess(cmdName, args, &os.ProcAttr{
				Files: []*os.File{logFd, logFd, logFd},
			})
			if err != nil {
				log.Fatal("daemon error:", err)
				return
			}
			log.Printf("Start-Deamon: run in daemon success, pid: %v\nlog : %s", newProc.Pid, logFile)

		} else {
			cmdName := args[0]
			newProc, err := os.StartProcess(cmdName, args, &os.ProcAttr{
				Files: []*os.File{nil, nil, nil},
			})

			if err != nil {
				log.Fatal("daemon error:", err)
				return
			}
			log.Printf("Start-Deamon: run in daemon success, pid: %v\n", newProc.Pid)

		}

		return
	}
}
